import request from '@/utils/request';
import { requestWrapper, randomDate, randomInt, randomPick, paginate } from '@/utils/mock';

// 获取定时任务列表
export function getJobList(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/monitor/job/list',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      // 任务组
      const jobGroups = ['DEFAULT', 'SYSTEM', 'MAIL', 'BACKUP'];
      // 错误策略（1立即执行，2执行一次，3放弃执行）
      const misfirePolicies = ['1', '2', '3'];
      // 是否并发执行（0禁止，1允许）
      const concurrents = ['0', '1'];
      // 状态（0暂停，1正常）
      const statusOptions = ['0', '1'];

      const jobs = Array.from({ length: 20 }, (_, index) => {
        const status = randomPick(statusOptions);
        return {
          jobId: index + 1,
          jobName: `任务${index + 1}`,
          jobGroup: randomPick(jobGroups),
          invokeTarget: `taskService.task${index + 1}`,
          cronExpression: index % 2 === 0 ? '0/10 * * * * ?' : '0 0 12 * * ?',
          misfirePolicy: randomPick(misfirePolicies),
          concurrent: randomPick(concurrents),
          status,
          createTime: randomDate(-30),
          nextValidTime: status === '1' ? randomDate(0, 1) : null
        };
      });

      // 处理搜索条件
      let filteredJobs = [...jobs];

      if (params) {
        if (params.jobName) {
          filteredJobs = filteredJobs.filter(item => 
            item.jobName.includes(params.jobName)
          );
        }
        
        if (params.jobGroup) {
          filteredJobs = filteredJobs.filter(item => 
            item.jobGroup.includes(params.jobGroup)
          );
        }
        
        if (params.status !== undefined && params.status !== '') {
          filteredJobs = filteredJobs.filter(item => 
            item.status === params.status
          );
        }
      }

      // 处理分页
      const pageNum = params?.pageNum ? parseInt(params.pageNum) : 1;
      const pageSize = params?.pageSize ? parseInt(params.pageSize) : 10;
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = pageNum * pageSize;
      const pageData = filteredJobs.slice(startIndex, endIndex);

      return paginate(pageData, pageNum, pageSize, filteredJobs.length);
    }
  );
}

// 获取定时任务详情
export function getJobDetail(jobId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/monitor/job/${jobId}`,
      method: 'get'
    }),
    // 模拟数据
    {
      jobId,
      jobName: `任务${jobId}`,
      jobGroup: 'DEFAULT',
      invokeTarget: `taskService.task${jobId}`,
      cronExpression: '0/10 * * * * ?',
      misfirePolicy: '1',
      concurrent: '1',
      status: '1',
      remark: `任务${jobId}的描述信息`,
      createTime: randomDate(-30),
      updateTime: randomDate(-10)
    }
  );
}

// 新增定时任务
export function addJob(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/monitor/job',
      method: 'post',
      data
    }),
    // 模拟数据
    {
      jobId: randomInt(100, 999)
    }
  );
}

// 更新定时任务
export function updateJob(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/monitor/job',
      method: 'put',
      data
    }),
    // 模拟数据
    null
  );
}

// 删除定时任务
export function deleteJob(jobIds) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/monitor/job/${jobIds}`,
      method: 'delete'
    }),
    // 模拟数据
    null
  );
}

// 执行定时任务
export function runJob(jobId) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: `/monitor/job/run/${jobId}`,
      method: 'post'
    }),
    // 模拟数据
    null
  );
}

// 更新定时任务状态
export function updateJobStatus(data) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/monitor/job/status',
      method: 'put',
      data
    }),
    // 模拟数据
    null
  );
}

// 获取定时任务日志列表
export function getJobLogList(params) {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/monitor/job/log/list',
      method: 'get',
      params
    }),
    // 模拟数据
    () => {
      // 任务组
      const jobGroups = ['DEFAULT', 'SYSTEM', 'MAIL', 'BACKUP'];
      // 状态（0失败，1成功）
      const statusOptions = ['0', '1'];

      const jobLogs = Array.from({ length: 30 }, (_, index) => {
        const status = randomPick(statusOptions);
        const jobId = randomInt(1, 10);
        return {
          jobLogId: index + 1,
          jobId,
          jobName: `任务${jobId}`,
          jobGroup: randomPick(jobGroups),
          invokeTarget: `taskService.task${jobId}`,
          jobMessage: status === '1' ? '执行成功' : '执行失败',
          status,
          exceptionInfo: status === '0' ? '错误详情：空指针异常' : '',
          createTime: randomDate(-30)
        };
      });

      // 处理搜索条件
      let filteredLogs = [...jobLogs];

      if (params) {
        if (params.jobName) {
          filteredLogs = filteredLogs.filter(item => 
            item.jobName.includes(params.jobName)
          );
        }
        
        if (params.jobGroup) {
          filteredLogs = filteredLogs.filter(item => 
            item.jobGroup.includes(params.jobGroup)
          );
        }
        
        if (params.status !== undefined && params.status !== '') {
          filteredLogs = filteredLogs.filter(item => 
            item.status === params.status
          );
        }
        
        if (params.beginTime && params.endTime) {
          filteredLogs = filteredLogs.filter(item => {
            const logTime = new Date(item.createTime).getTime();
            const beginTime = new Date(params.beginTime).getTime();
            const endTime = new Date(params.endTime).getTime();
            return logTime >= beginTime && logTime <= endTime;
          });
        }
      }

      // 处理分页
      const pageNum = params?.pageNum ? parseInt(params.pageNum) : 1;
      const pageSize = params?.pageSize ? parseInt(params.pageSize) : 10;
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = pageNum * pageSize;
      const pageData = filteredLogs.slice(startIndex, endIndex);

      return paginate(pageData, pageNum, pageSize, filteredLogs.length);
    }
  );
}

// 清空定时任务日志
export function cleanJobLog() {
  return requestWrapper(
    // 真实API请求
    () => request({
      url: '/monitor/job/log/clean',
      method: 'delete'
    }),
    // 模拟数据
    null
  );
} 